/*
* ============================================================================
*  Name        : sea_meta_system.cpp
*  Part of     : Finite state machine utilities
*  Description : Meta system implementation
*  Version     : %version: %
*  
*
* ============================================================================
*/
#include "sea_meta_system.h"
#include "sea.h"

/**
 * @file sea_meta_system.cpp
 * @brief Meta system keeps all the records( @ref sea::MetaSystemRegistryEntry ) 
 * of classes and their state machines bodies <br>
 * in global repository - @ref sea::GlobalMetaSystemRegistry
 *
 * @ingroup StateMachineFramework
 */
using namespace sea;

// -------------------------------------------------------------------------------------------------
// Dtor
// -------------------------------------------------------------------------------------------------
MetaSystemRegistryEntry::~MetaSystemRegistryEntry( )
{ 
}

// -------------------------------------------------------------------------------------------------
// Register new state machine class
// -------------------------------------------------------------------------------------------------
sea::ref< MetaSystemRegistryEntry > MetaSystem::insert( String name )
{
    OsMutex::Scoped safe( &GlobalMetaSystemRegistry::m_lock );

    sea::ref< MetaSystemRegistryEntry > registry_entry = GlobalMetaSystemRegistry::get( )[ name ];

    // Check if entry has been already added to the registry
    if ( registry_entry == NULL )
    {
        // Create map entry: class name -> meta data registry
        registry_entry << NEW MetaSystemRegistryEntry( name );
        if ( registry_entry == NULL )
        {
            return NULL;
        }
        GlobalMetaSystemRegistry::get( )[ name ] = registry_entry;
    }

    return registry_entry;
}

// -------------------------------------------------------------------------------------------------
// Destroy meta system registry
// -------------------------------------------------------------------------------------------------
void MetaSystem::destroy( )
{
#if !defined( STATIC_META_DATA_ENABLED )

    OsMutex::Scoped safe( &GlobalMetaSystemRegistry::m_lock );

    if ( !GlobalMetaSystemRegistry::m_meta_system_registry )
    {
        // Never was created
        return;
    }

    // Delete system state machine object
    delete StateMachine::m_system;
    StateMachine::m_system = NULL;

    // Destroy global registry. Dont leave anything to
    // be killed by static objects destructors
    // Not all platforms support that as they should
    delete GlobalMetaSystemRegistry::m_meta_system_registry;
    GlobalMetaSystemRegistry::m_meta_system_registry = NULL;

#endif
}

// -------------------------------------------------------------------------------------------------
